package cn.creditease.std.factory.impl;

import cn.creditease.std.JobAlloter;
import cn.creditease.std.context.JobAlloterContext;
import cn.creditease.std.factory.JobAlloterFactory;
import cn.creditease.std.producer.Producer;
import cn.creditease.std.producer.impl.MqProducerImpl;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @Description: 默认的任务生产工厂实现，此对象jvm全局唯一，不需要每个任务单独创立
 * @Author: kai.yang
 * @Date: 2019-08-02 14:51
 */
public class DefaultMQJobAlloterFactoryImpl implements JobAlloterFactory {

    private static final Logger logger = LoggerFactory.getLogger(DefaultMQJobAlloterFactoryImpl.class);


    RabbitTemplate rabbitTemplate;


    ConnectionFactory connectionFactory;


    /**
     * 限制必须通过init构造
     */
    public DefaultMQJobAlloterFactoryImpl(RabbitTemplate rabbitTemplate, ConnectionFactory connectionFactory) {
        this.rabbitTemplate = rabbitTemplate;
        this.connectionFactory = connectionFactory;
    }


    @Override
    public DataSource getDateSource() {
        return JobAlloterContext.getContext().getDataSource();
    }


    @Override
    public int getMaxJobSize(String jobName) {
        return JobAlloterContext.getContext().getJobConsumerConfigMap().get(jobName).getMaxJobCount();
    }


    @Override
    public List<Producer> getProducers() {
        return producers.values().stream().collect(Collectors.toList());
    }


    /**
     * 开的mq监听能力
     */
    @Override
    public JobAlloterFactory startLisenter() {
        if (rabbitTemplate != null && connectionFactory != null) {
            try {
                return this.addProducer(new MqProducerImpl(rabbitTemplate, connectionFactory));
            } catch (IOException e) {
                logger.error("新增mq channel失败", e);
            }
        }
        return this;
    }

    @Override
    public JobAlloter getAlloter(int sum, String jobGroupName, int maxDuration) {
        return JobAlloter.builder()
            .dataSource(getDateSource())
            .jobGroupName(jobGroupName)
            .maxJobCount(getMaxJobSize(jobGroupName))
            .maxDuration(maxDuration)
            .producers(getProducers())
            .sum(sum).build();

    }


}
